﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Cfg;
using System.Web;

namespace NHBLL
{
    public sealed class NHelper
    {
        private const string CurrentSessionKey = "nhibernate.current_session";
        private static readonly ISessionFactory sessionFactory;
        [ThreadStatic]//声明为线程共享
        public static ISession sessionWin;//winform程序使用


        static NHelper()
        {
            try
            {
                sessionFactory = new Configuration().Configure().BuildSessionFactory();
            }
            catch (Exception ee)
            {
                throw ee;
            }
        }

        public static ISession GetCurrentSession()
        {
            CloseSession();
            HttpContext context = HttpContext.Current;//webform程序使用
            if (context != null)
            {
                ISession currentSession = context.Items[CurrentSessionKey] as ISession;
                if (currentSession == null)
                {
                    currentSession = sessionFactory.OpenSession();
                    context.Items[CurrentSessionKey] = currentSession;
                }
                return currentSession;
            }
            else//winform程序使用
            {
                if (sessionWin.Equals(null))
                {
                    sessionWin = sessionFactory.OpenSession();
                }
                return sessionWin;
            }

        }

        public static void CloseSession()
        {
            HttpContext context = HttpContext.Current;
            //web程序
            if (context != null)
            {
                ISession currentSession = context.Items[CurrentSessionKey] as ISession;
                if (currentSession == null)
                {
                    return;
                }
                currentSession.Close();
                context.Items.Remove(CurrentSessionKey);
            }
            //window程序
            else
            {
                if (sessionWin.Equals(null))
                {
                    return;
                }
                sessionWin.Close();
                sessionWin = null;
            }

        }

        public static void CloseSessionFactory()
        {
            if (sessionFactory != null)
            {
                sessionFactory.Close();
            }
        }
    }
}
